const net = require('net');
const { LedInterface } = require('./utils/ledInterface');
const { FrontendHandler } = require('./handlers/frontendHandler');
const { BackendHandler } = require('./handlers/backendHandler');

class ProxyServer {
    constructor() {
        // 初始化LED接口数据
        this.ledInterface = new LedInterface();
        
        // 创建TCP服务器
        this.server = net.createServer((frontendSocket) => {
            console.log('飞控软件已连接');
            
            // 创建与LED显示屏的连接
            const backendSocket = new net.Socket();
            
            // 初始化处理器
            const frontendHandler = new FrontendHandler(frontendSocket, backendSocket, this.ledInterface);
            const backendHandler = new BackendHandler(backendSocket, frontendSocket, this.ledInterface);
            
            // 处理飞控软件数据
            frontendSocket.on('data', (data) => {
                frontendHandler.handleData(data);
            });
            
            // 处理LED显示屏数据
            backendSocket.on('data', (data) => {
                backendHandler.handleData(data);
            });
            
            // 错误处理
            frontendSocket.on('error', (err) => {
                console.error('飞控软件连接错误:', err);
                backendSocket.destroy();
            });
            
            backendSocket.on('error', (err) => {
                console.error('LED显示屏连接错误:', err);
                frontendSocket.destroy();
            });
            
            // 连接关闭处理
            frontendSocket.on('close', () => {
                console.log('飞控软件连接已关闭');
                backendSocket.destroy();
            });
            
            backendSocket.on('close', () => {
                console.log('LED显示屏连接已关闭');
                frontendSocket.destroy();
            });
        });
    }
    
    // 启动服务器
    start(localPort, remoteHost, remotePort) {
        // 监听本地端口
        this.server.listen(localPort, () => {
            console.log(`代理服务器启动在端口 ${localPort}`);
            console.log(`转发到 ${remoteHost}:${remotePort}`);
        });
        
        // 服务器错误处理
        this.server.on('error', (err) => {
            console.error('服务器错误:', err);
        });
    }
}

// 创建并启动服务器实例
const proxyServer = new ProxyServer();

// 配置参数
const LOCAL_PORT = process.env.LOCAL_PORT || 8080;        // 本地监听端口
const REMOTE_HOST = process.env.REMOTE_HOST || '127.0.0.1'; // LED显示屏IP
const REMOTE_PORT = process.env.REMOTE_PORT || 5000;      // LED显示屏端口

// 启动服务器
proxyServer.start(LOCAL_PORT, REMOTE_HOST, REMOTE_PORT);

// 优雅退出处理
process.on('SIGINT', () => {
    console.log('正在关闭服务器...');
    proxyServer.server.close(() => {
        console.log('服务器已关闭');
        process.exit(0);
    });
});

module.exports = ProxyServer;
